package com.piece.core.session.strategy;

import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.framework.constant.ExceptionAuthConstants;
import com.piece.core.web.util.ServletUtil;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 抽象的session失效处理器
 */
public class AbstractSessionStrategy {

	/**
	 * 跳转的url
	 */
	private String destinationUrl;
	/**
	 * 重定向策略
	 */
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	/**
	 * 跳转前是否创建新的session
	 */
	private boolean createNewSession = true;

	public AbstractSessionStrategy(String invalidSessionUrl) {
		Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl), "url must start with '/' or with 'http(s)'");
		this.destinationUrl = invalidSessionUrl;
	}

	/**
	 * Session失效跳转
	 */
	protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (this.createNewSession) {
			request.getSession();
		}

		if (ServletUtil.isAjaxRequest(request)) {
			String message = I18nUtil.message(ExceptionAuthConstants.LOGIN_RETRY);
			if (isConcurrency()) {
				message = I18nUtil.message(ExceptionAuthConstants.LOGIN_MAX);
			}
			ServletUtil.renderString(response, JsonUtil.toJson(AjaxResponse.error(message)));
		} else {
			this.redirectStrategy.sendRedirect(request, response, this.destinationUrl);
		}
	}

	protected void setCreateNewSession(boolean createNewSession) {
		this.createNewSession = createNewSession;
	}

	protected boolean isConcurrency() {
		return false;
	}
}
